<script setup>
import { use } from 'echarts/core'
import { PieChart } from 'echarts/charts'
import { 
  TitleComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import { ref, watch } from 'vue'

// 注册必要的组件
use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer
])

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  title: {
    type: String,
    default: ''
  },
  height: {
    type: String,
    default: '400px'
  }
})

const option = ref({
  title: {
    text: props.title,
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left',
    data: props.data.map(item => item.name)
  },
  series: [
    {
      name: '数量',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: props.data
    }
  ]
})

watch(() => props.data, (newVal) => {
  option.value.series[0].data = newVal
  option.value.legend.data = newVal.map(item => item.name)
}, { deep: true })

watch(() => props.title, (newVal) => {
  option.value.title.text = newVal
})
</script>

<template>
  <v-chart class="chart" :option="option" :style="{ height }" />
</template>

<style scoped>
.chart {
  width: 100%;
}
</style>